<template>
  <a-card>
    <template #title>
      <span class="head_title"> {{ isEdit ? '修改范围' : '新增范围' }}</span>
    </template>
    <div slot="extra" class="head_btn">
      <div class="head_btn_router">
        <span>预警设置</span>
        <span class="head_btn_router_blod">/地图范围设置</span>
      </div>
      <img slot="extra" class="cursor_pointer" src="@/assets/images/accept/back-button.png" alt="返回按钮" @click="back">
    </div>
    <div id="m">
      <MapTencentCom
        ref="map"
        :zoom="16"
        :pitch="30"
        :callback="true"
        :isShowBtn="true"
        @callback="callBack"
        @confirm="confirm"
      />
      <a-modal v-model="openModel" title="确认保存范围？" @ok="finish">
        <a-form-model ref="myForm" :model="info" :rules="rules" :label-col="{span: 4}" :wrapper-col="{span: 20}">
          <a-form-model-item label="位置描述" prop="name">
            <a-input
              placeholder="请输入位置描述"
              v-model="info.name"
            />
          </a-form-model-item>
          <a-form-model-item label="范围类型" prop="areatype">
            <!-- style="width: 220px;font-weight: normal" -->
            <a-select v-model="info.areatype" placeholder="请选择范围类型" allowClear>
              <a-select-option v-for="area in Tp_crc_areatypeList" :key="area.value" :value="area.value">
                {{ area.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>
  </a-card>
</template>
<script>
import { existsGeopointName, saveGeopoint, viewGeopoint } from '@/api/correction/crc_geopoint'
import moment from 'moment'
import storage from 'store'
import { APP_USER } from '@/store/mutation-types'
import MapTencentCom from '@/views/visualization/map/MapTencent_com.vue'
import { Tp_crc_areatypeList } from '@/enumeration/correction/Tp_crc_areatype'
export default {
  components: {
    MapTencentCom,
    SelectCorrectPerson: () => import('@/views/correction/warning/SelectCorrectPerson.vue')
  },
  data () {
    return {
      info: {
        id: undefined,
        name: undefined,
        geopoints: undefined,
        areatype: undefined,
        createuserid: undefined,
        createusername: undefined,
        createtime: undefined
      },
      rules: {
        name: [
          { required: true, message: '请输入位置描述', trigger: 'blur' },
          { min: 1, max: 33, message: '位置描述最大长度不能超过33', trigger: 'blur' }
        ],
        areatype: [
          { required: true, message: '请选择范围类型', trigger: 'change' }
        ]
      },
      Tp_crc_areatypeList: Tp_crc_areatypeList,
      openModel: false,
      initMap: false,
      ruleId: undefined,
      isEdit: false
    }
  },
  watch: {
    initMap () {
      document.getElementById("drawStart").click()
      console.log('drawLayer', this.$refs.map.drawLayer)
      this.$refs.map.drawLayer.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT)
      this.$refs.map.drawLayer.setSelectable(true)
      this.setGeopoints()
    }
  },
  methods: {
    async finish () {
      let validateFlag
      this.$refs.myForm.validate(valid => {
        validateFlag = valid
      })
      if (!validateFlag) {
        this.$message.warning('请填写必填信息！')
        return
      }
      // 新增范围校验是否存在同名规则
      if (!this.isEdit) {
        const existsResult = await existsGeopointName(this.info.name)
        if (existsResult.code !== 0) {
          this.$message.error('校验地图描述是否存在失败!')
          return
        }
        if (existsResult.data) {
          this.$message.error('该位置描述已存在，请换个描述!')
          return
        }
      }

      const { code } = await saveGeopoint(this.info)
      if (code !== 0) {
        this.$message.error('保存地图范围坐标设置失败!')
        return
      }
      this.$message.success('保存成功')
      this.back()
    },
    cancel () {
      this.back()
    },
    back () {
      if (this.$refs.map.drawLayer) {
        this.$refs.map.drawLayer.destroy()
      }
      this.$refs.map.map.destroy()
      this.$refs.map.$destroy()
      this.$router.push({
        path: '/CorrectGeopoint',
        query: this.$route.query
      })
    },
    callBack (map) {
      console.log('callBack')
      this.$refs.map.showDraw()
      console.log('地图信息', map)
    },
    setGeopoints () {
      const areas = JSON.parse(this.info.geopoints)
      const geopoints = []
      const points = []
      for (let i = 0; i < areas.length; i++) {
        geopoints.push({
          paths: []
        })
        for (let j = 0; j < areas[i].length; j++) {
          points.push(areas[i][j].lat + ',' + areas[i][j].lng)
          geopoints[i].paths.push(new TMap.LatLng(areas[i][j].lat, areas[i][j].lng))
        }
      }
      console.log('drawPolygon', this.$refs.map.drawPolygon)
      this.$refs.map.drawPolygon.setGeometries(geopoints)
      console.log(geopoints[0].paths[0].lat, geopoints[0].paths[0].lng)
      this.$refs.map.setCenter(...this.getPointsCenter(points))
    },
    getPointsCenter (points) {
      const pointNum = points.length
      let X = 0; let Y = 0; let Z = 0
      for (let i = 0; i < points.length; i++) {
        if (points[i] === '') {
          continue
        }
        const point = points[i].split(',')
        let lat, lng, x, y, z
        lat = parseFloat(point[0]) * Math.PI / 180
        lng = parseFloat(point[1]) * Math.PI / 180
        x = Math.cos(lat) * Math.cos(lng)
        y = Math.cos(lat) * Math.sin(lng)
        z = Math.sin(lat)
        X += x
        Y += y
        Z += z
      }
      X = X / pointNum
      Y = Y / pointNum
      Z = Z / pointNum

      const tmpLng = Math.atan2(Y, X);
      const tmpLat = Math.atan2(Z, Math.sqrt(X * X + Y * Y))

      return [tmpLat * 180 / Math.PI, tmpLng * 180 / Math.PI]
    },
    confirm (drawPolygon) {
      if (
        drawPolygon.geometries != null &&
        drawPolygon.geometries.length > 0
      ) {
        const areas = []
        for (let r = 0; r < drawPolygon.geometries.length; r++) {
          const points = []
          for (
            let x = 0;
            x < drawPolygon.geometries[r].paths.length;
            x++
          ) {
            const item = drawPolygon.geometries[r].paths[x]
            points.push({ lat: item.lat, lng: item.lng })
          }
          areas.push(points)
          this.info.geopoints = JSON.stringify(areas)
          this.openModel = true
        }
      } else {
        this.$message.warning('请选择范围')
      }
    }
  },
  async created () {
    this.ruleId = this.$route.query.ruleId
    if (this.ruleId) {
      this.isEdit = true
      const { code, data } = await viewGeopoint(this.ruleId)
      if (code !== 0) {
        this.$message.error('未获取到地图范围详细信息')
        return
      }
      this.info = data
      this.initMap = true
    } else {
      this.isEdit = false
      const today = moment().format('YYYY-MM-DD HH:mm:ss')
      this.info.name = '地图范围位置-' + today
      this.info.createuserid = storage.get(APP_USER).userId
      this.info.createusername = storage.get(APP_USER).fullname
      this.info.createtime = today
    }
  }
}
</script>

<style lang="scss" scoped>
  #m {
    position: sticky;
  }

  .head_title {
    font-size: 24px;
    font-family: "PingFang-SC-Heavy";
    font-weight: 800;
    color: #2C2C2C;
    margin-left: 10px;
  }

  .head_btn {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;    

    &_router {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;   
      margin-left:30px;

      font-size: 16px;
      font-family: "PingFang-SC-Heavy";
      font-weight: 800;
      color: #999999;

      &_blod {
        font-size: 16px;
        font-family: "PingFang-SC-Heavy";
        font-weight: 800;
        color: #2C2C2C;
        margin-left: 10px;
        margin-right: 20px;
      }
    }
  }
</style>
